package com.prizedraw.prize_draw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prizedraw.prize_draw.common.dp.LuckInfo;
import com.prizedraw.prize_draw.common.dto.LuckyDrawDto;
import com.prizedraw.prize_draw.common.sheet.LuckUser;
import com.prizedraw.prize_draw.entity.*;
import com.prizedraw.prize_draw.mapper.DepartmentMapper;
import com.prizedraw.prize_draw.mapper.DrawMapper;
import com.prizedraw.prize_draw.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author czj666
 * @since 2021-09-07
 */
@Slf4j
@Service
public class DrawServiceImpl extends ServiceImpl<DrawMapper, Draw> implements DrawService {
    @Autowired
    DepartmentService departmentService;

    @Autowired
    DepartmentDrawService departmentDrawService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    DrawService drawService;

    @Autowired
    PrizeService prizeService;

    @Autowired
    DrawMapper drawMapper;

    @Autowired
    DrawRecordService drawRecordService;

    @Autowired
    DepartmentMapper departmentMapper;

    /**
     * 通过活动ID显示参与的人
     * @param drawId
     * @return
     */
    @Override
    public List<SysUser> listUserByDrawId(Integer drawId) {

        List<Integer> userIds = drawMapper.getUserIdsByDrawId(drawId);
        return sysUserService.listByIds(userIds);
//        //获取部门ID
//        List<DepartmentDraw> departmentDrawList = departmentDrawService.list(new QueryWrapper<DepartmentDraw>()
//                .eq("draw_id", id));
//        List<Integer> deptIds = departmentDrawList.stream().map(dd -> dd.getDeptId()).collect(Collectors.toList());
//
//        //根据有资格抽奖的部门ID查找所有人
//        List<SysUser> users = new ArrayList<>();
//        for (Integer deptId : deptIds) {
////            List<SysUser> usersByDept = sysUserService.list(new QueryWrapper<SysUser>()
////                    .eq("dept_id", deptId).select("id","user_id","user_name","dept_id","gender","hiredate"));
//            sysUserService.list(new QueryWrapper<SysUser>().inSql("id","select DISTINCT user_id from user_department_role where department_role_id in ()"))
////            for (SysUser user : usersByDept) {
////
////                //查找该人的角色
////                List<SysRole> sysRoles = sysUserService.listRoleByUserId(user.getUserId());
////                user.setSysRoles(sysRoles);
////                users.add(user);
////            }
//        }
    }

    /**
     * 根据活动ID获取活动信息
     * @param drawId
     * @return
     */
    @Override
    public Draw listDrawByDrawId(Integer drawId) {

        Draw draw = drawService.getById(drawId);
        //获取部门范围
        List<DepartmentDraw> departmentDrawList = departmentDrawService.list(new QueryWrapper<DepartmentDraw>()
                .eq("draw_id", drawId));
        List<Integer> deptIds = departmentDrawList.stream().map(d -> d.getDeptId()).collect(Collectors.toList());

        List<Department> departments = departmentService.listByIds(deptIds);
        draw.setDrawScope(departments);

        //获取奖项
        List<Prize> prizes = prizeService.list(new QueryWrapper<Prize>().eq("draw_id", drawId));
        draw.setPrizeList(prizes);
        return draw;
    }

    /**
     * 根据draw对象保存到数据库
     * @param draw
     */
    @Override
    public void saveInfo(Draw draw) {
        //添加活动表
        Date date = new Date();
        draw.setReleaseTime(date);
        draw.setState(1);
        drawService.save(draw);

        //获取活动ID
        int drawId = draw.getId();

        //添加部门-活动表
        int size = draw.getDrawScope().size();

        List<Department> drawScope = draw.getDrawScope();
        List<Integer> departmentIds = drawScope.stream().map(ds -> ds.getId()).collect(Collectors.toList());

        List<DepartmentDraw> departmentDraws = new ArrayList<DepartmentDraw>();

        for (int i = 0;i < size; i ++){
            DepartmentDraw departmentDraw = new DepartmentDraw();
            departmentDraw.setDrawId(drawId);
            departmentDraw.setDeptId(departmentIds.get(i));
            departmentDraws.add(departmentDraw);
        }
        departmentDrawService.saveBatch(departmentDraws);

        //添加奖项表
        List<Prize> prizeList = draw.getPrizeList();
        for (Prize prize : prizeList) {
            prize.setDrawId(drawId);
        }
        prizeService.saveBatch(prizeList);
    }

    //判断活动参与人数是否大于奖项人数
    @Override
    public boolean matchNum(Draw draw) {
        //获取设置范围的所有人的人数

        Set<Integer> userSet = new HashSet<>();
        for (Department department : draw.getDrawScope()) {
            List<Integer> userIds = departmentMapper.getUserIdsByDeptId(department.getId());
            for (Integer userId : userIds) {
                userSet.add(userId);
            }
        }
        //获取奖项设置的所有的人数
        List<Prize> prizeList = draw.getPrizeList();
        int prizeNumSize = 0;
        for (Prize prize : prizeList) {
            prizeNumSize = prizeNumSize + prize.getDrawNum();
        }
        if (userSet.size() > prizeNumSize){
            return true;
        }else {
            return false;
        }

    }

    @Override
    public List<LuckyDrawDto> getLuckyUsersById(Integer id) {
        //抽奖结果集合
        List<LuckyDrawDto> luckyDrawDtos = new ArrayList<>();

        List<Prize> prizeList = prizeService.list(new QueryWrapper<Prize>().eq("draw_id", id));

        List<DrawRecord> drawRecords = drawRecordService.list(new QueryWrapper<DrawRecord>().eq("draw_id", id));

        for (Prize prize : prizeList) {
            //单个奖项结果集
            LuckyDrawDto luckyDrawDto = new LuckyDrawDto();
            Draw draw = drawService.getById(id);
            luckyDrawDto.setDrawName(draw.getTitle());
            luckyDrawDto.setPrizeId(prize.getId());
            luckyDrawDto.setDrawId(id);
            luckyDrawDto.setTitle(prize.getTitle());
            luckyDrawDto.setPrizeName(prize.getPrizeName());

            List<SysUser> sysUsers = new ArrayList<>();

            for (DrawRecord drawRecord : drawRecords) {
                if(drawRecord.getPrizeId() == prize.getId()){
                    SysUser luckyUser = sysUserService.getOne(new QueryWrapper<SysUser>()
                            .eq("id", drawRecord.getUserId())
                            .select("id","user_id","user_name","gender","phone_num","hiredate"));
                    sysUsers.add(luckyUser);
                }

            }
            luckyDrawDto.setUsers(sysUsers);

            luckyDrawDtos.add(luckyDrawDto);

        }
        return luckyDrawDtos;
    }

    /*@Override
    public void exportLuckInfo(Integer id, HttpServletResponse response) {

        //获取全部获奖人员信息对象
        List<LuckInfo> LuckInfoList=drawMapper.selectprize(id);
        List<LuckUser> list = new ArrayList<>();
        LuckUser userSheet = null;
        for (int i = 0; i < LuckInfoList.size(); i++) {
            userSheet = new LuckUser();
            //获取数据库的用户集合
            LuckInfo luckInfo = LuckInfoList.get(i);
            //对集合依次写入表格中
            userSheet.setTitle(luckInfo.getTitle());
            userSheet.setPrizeName(luckInfo.getPrizeName());
            userSheet.setUserId(luckInfo.getUserId());
            userSheet.setUserName(luckInfo.getUserName());
            userSheet.setPhoneNum(luckInfo.getPhoneNum());
            list.add(userSheet);
        }
        //文件名称
        String fileName = "抽奖结果";
        //表格sheet名称(用过excel应该知道什么是这个名称)
        String sheetName = "抽奖结果";
        System.out.println(LuckInfoList);
//        ExcelUtil.writeExcel(response, list, fileName, sheetName, new LuckUser());
    }*/

    //根据用户ID查历史参与的活动
    @Override
    public List<Draw> getUserDrawById(Integer id) {
        List<Integer> drawIds = drawMapper.getUserDrawById(id);
        List<Draw> drawList = new ArrayList<>();
        for (Integer drawId : drawIds) {
            Draw draw = drawService.listDrawByDrawId(drawId);
            if (draw.getState() == 0){
                drawList.add(draw);
            }
        }
        return drawList;
    }

    //根据用户ID查所属部门的活动
    @Override
    public List<Draw> getDeptDrawById(Integer id) {
        List<Integer> drawIds = drawMapper.getUserDrawById(id);
        List<Draw> drawList = new ArrayList<>();
        for (Integer drawId : drawIds) {
            Draw draw = drawService.listDrawByDrawId(drawId);
            if (draw.getState() == 1){
                drawList.add(draw);
            }
        }
        return drawList;
    }
}
